import VueConfig, { preffix } from '__CONFIG__/vue-config.js'

const RequestDispose = {
  install(Vue, options) {
    function baseDeal(res, openBaseDealTip = true) {
      const {data, status, message} = res
      const VUE_CALLBOARD = Vue.prototype[VueConfig[preffix+'CALLBOARD'].name] // 播报
      const { error: $Error, state: $State, success: $Success } = VUE_CALLBOARD
      if(status === 'success') {//注册成功
        return Promise.resolve({data, message})
      }else if(status === 'error') {//注册失败
        const messageType = typeof message
        let resultMessage
        if(messageType === 'string') { //字符串
          resultMessage = message.replace(/ResponseError: /, '')
        }else if('object') {
          resultMessage = message.errors.map((error)=>(error.field)).join(', ') + ' is required'
        }
        //是否开启提示服务
        if(openBaseDealTip) {
          $Error({
            title: '警告',
            desc: `服务器意料之内的错误: ${resultMessage}`,
            duration: 3000
          })
        }
        return Promise.reject({message: resultMessage, messageAuthor: 'developer'})
      }else {
        console.log('服务端返回结果意外')
      }
    }
    //挂载到vue上去
    Vue.prototype.$RequestDispose = baseDeal

    VueConfig[preffix+'REQUEST_DISPOSE'] = {
      name: '$RequestDispose',
      type: 'plugn'
    }

    function dealConnectionError(error) {
      const VUE_CALLBOARD = Vue.prototype[VueConfig[preffix+'CALLBOARD'].name] // 播报
      const { error: $Error, state: $State, success: $Success } = VUE_CALLBOARD
      $State({
        title: '连接远端失败',
        desc: '服务器不够强，可能无法加载数据，等待几秒后请刷新几次重新加载，请谅解',
        duration: 3000
      })
      return error
    }
    baseDeal.$ConnectionErrorDispose =  dealConnectionError
  }
}

export default RequestDispose